import { defineStore } from "pinia";

// 用户信息接口
export interface UserInfo {
    username: string;
    id: number;
    role: string;
}
// 账户信息接口
export interface AccountInfo {
    userInfo?: UserInfo;
    token?: string
}
// 持久化存储键名
const localStorageKey = 'shop.user';
// 共享的状态仓库
export const useAccountStore = defineStore('loginState', {
    // 账户状态数据
    state: (): AccountInfo => {
        // 尝试读取本地缓存数据
        let localInfo = localStorage.getItem(localStorageKey);
        let accountInfo: AccountInfo = {};
        if (localInfo) {
            accountInfo = JSON.parse(localInfo);
        }
        // 初始化账户数据
        return {
            userInfo: accountInfo.userInfo,
            token: accountInfo.token,
        }
    },
    // 计算属性
    getters: {
        // 当前登录态
        isLogin: (state) => {
            return (state.token && state.token.length > 0);
        }
    },
    // 定义行为
    actions: {
        // 登录行为
        login(info: AccountInfo) {
            this.userInfo = info.userInfo;
            this.token = info.token;
            // 将账户数据编码为JSON字符串后存储到本地
            localStorage.setItem(localStorageKey, JSON.stringify(info));
        },
        // 登出行为
        logout() {
            // 清空数据
            this.userInfo = undefined;
            this.token = undefined;
            localStorage.removeItem(localStorageKey)
        }
    }
});